package com.hdc.hdc.warehouseManage.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.Path;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.hdc.hdc.warehouseManage.entity.GoodsAndLocations;
import com.hdc.hdc.warehouseManage.entity.GoodsLocation;
import com.hdc.hdc.warehouseManage.entity.GoodsTrade;
import com.hdc.hdc.warehouseManage.entity.vo.WareHouseVO;
import com.hdc.hdc.warehouseManage.repository.GoodsAndLocationRepository;
import com.hdc.hdc.warehouseManage.repository.GoodsLocationRepository;
import com.hdc.hdc.warehouseManage.repository.WareHouseRepository;
import com.hdc.hdc.warehouseManage.service.GoodsLocationServiceI;

@Service
public class GoodsLocationServiceImpl implements GoodsLocationServiceI {

	@Autowired
	private GoodsLocationRepository goodLocationRepository;
	
	@Autowired
	private WareHouseRepository wareHouseRepository;
	
	@Autowired
	private GoodsAndLocationRepository goodsAndLocationRepository;
	
	@Override
	public List<GoodsLocation> findGoodLocation() {
		
		List<GoodsLocation> los = new ArrayList<GoodsLocation>(10);
		
		los = this.goodLocationRepository.findAll();
		
		return los;
	}

	@Override
	public Page<GoodsTrade> findGoodsTradeByLocation(Integer pageNum, Integer pageSize, String locationId) {

		Pageable pa = PageRequest.of(pageNum, pageSize);
		
		Specification<GoodsTrade> spec = (root, query, cb) -> {
			
			 Path<String> tPath = root.get("locationId");
			 
			 return cb.equal(tPath, locationId);
		};
		
		Specification<GoodsTrade> s = Specification.where(spec);
		
		Page<GoodsTrade> page = this.wareHouseRepository.findAll(s, pa);
		
		return page;
	}

	public void updateGoodsAndLocations(WareHouseVO vo) {
		

		this.wareHouseRepository.updateGoodsByVO(vo.getId(),vo.getLocationId(),vo.getLocationName(),
				vo.getWarningValue(),new Date());
		
		//先删掉物资与货位中间表的货位跟物资ID对应的数据，一个物资只能对应一个货位
		this.goodsAndLocationRepository.deleteByGoodsId(vo.getId());
		
		//添加会物资与货位的对应关系
		GoodsAndLocations gals = new GoodsAndLocations();
		gals.setGoodsId(vo.getId());
		gals.setLocationId(vo.getLocationId());
		
		if(vo.getWarningValue() != null) {
			gals.setGoodsNum(vo.getWarningValue());
		}
		
		this.goodsAndLocationRepository.save(gals);
	}

	@Override
	public List<GoodsTrade> findGoodsByHPL(String houseId, String positionId, String locationId) {
		
		return this.wareHouseRepository.findByHouseIdAndPositionIdAndLocationId(houseId,positionId,locationId);
	}

}
